package cc.ufinity.networkdiagnose.widget;

import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.regex.*;

public class HttpConfigWidget extends GeneralTestWidget implements View.OnClickListener {

    public final static String PREFS_HTTP_NAME = "http";
    public final static String PREFS_HTTP_KEY = "url";

    private Activity ctx;
    private Button btnSave;
    private Button btnBack;
    private EditText url;

    public HttpConfigWidget(Activity context) {
        super(context);
        this.ctx = context;
        inflate(context, R.layout.http_config, this);
        btnSave = (Button) this.findViewById(R.id.btn_httpcfg_save);
        btnBack = (Button) this.findViewById(R.id.btn_httpcfg_back);
        url = (EditText) this.findViewById(R.id.httpcfgeditText);
        btnSave.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_HTTP_NAME, 0);
        String tel = settings.getString(PREFS_HTTP_KEY, "");
        url.setText(tel);
    }

    private void save() {
        String input = url.getText().toString().trim();
        Pattern pattern = Pattern.compile("^(((ht|f)tp(s?))\\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\\-\\.]+\\.(com|cn|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\;\\?\\'\\\\+&amp;%\\$#\\=~_\\-]+))*$");
        Matcher matcher = pattern.matcher(input);
        boolean m1 = matcher.matches();
        if (StringUtils.isEmpty(input)) {
           showMessage(ctx, "请输入网址.");
        } 
        else if(!m1 ){
        	showMessage(ctx, "输入网址不合法，请重新输入！");
        }else {
            SharedPreferences settings = ctx.getSharedPreferences(PREFS_HTTP_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(PREFS_HTTP_KEY, input);
            editor.commit();
            showMessage(ctx, "网址已保存.");
            this.backToConfig(ctx);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_httpcfg_save:
            save();
            break;
        case R.id.btn_httpcfg_back:
            this.backToConfig(ctx);
            break;
        }
    }

    
}
